﻿using CodeNotes.BLL;
using CodeNotes.Common;
using CodeNotes.Model;
using MvcCodeNotes.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using ThoughtWorks.QRCode.Codec;

namespace MvcCodeNotes.Controllers
{
    public class QrcodeController : Controller
    {
        JavaScriptSerializer Serializer = new JavaScriptSerializer();
        //个性化二维码小程序参数
        public string AppId = "wx10dfbf29ad4f7d72";
        public string AppSecret = "d18fdd7cfc22923e2ab13821e54700d1";

        //
        // GET: /Qrcode/

        public ActionResult Index()
        {
            return View();
        }

        //门店待删除图片
        public ActionResult SiteTempImages()
        {
            return View();
        }

        public ActionResult Test()
        {

            return View();
        }

        #region 图片分类

        public ActionResult TemplateType(int? page)
        {
            int pageSize = 10;
            int pageIndex = page == null ? 0 : Convert.ToInt32(page);
            List<Wx_TemplateImageType> listTemp = new Wx_TemplateImageTypeLogic().GetModelList("");

            Pagination<Wx_TemplateImageType> paginateNew = new Pagination<Wx_TemplateImageType>(listTemp, pageIndex, pageSize);
            return View(paginateNew);
        }
        public ActionResult TemplateTypeEdit(int? id)
        {
            Wx_TemplateImageType model = new Wx_TemplateImageType();
            if (id != null)
            {
                model = new Wx_TemplateImageTypeLogic().GetModel(Convert.ToInt32(id));
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult TemplateTypeCreate(Wx_TemplateImageType model)
        {
            if (model.TypeId > 0)
                new Wx_TemplateImageTypeLogic().Update(model);
            else
                new Wx_TemplateImageTypeLogic().Add(model);
            return RedirectToAction("TemplateType");

        }

        [HttpPost]
        public ActionResult TemplateTypeDelete(int id)
        {
            try
            {
                if (id > 0)
                {
                    new Wx_TemplateImageTypeLogic().Delete(id);
                }

                return RedirectToAction("TemplateType");
            }
            catch
            {
                return View();
            }
        }

        #endregion

        #region 背景图片

        public ActionResult TemplateImage(int? page, int? typeid)
        {
            int pageSize = 10;
            int pageIndex = page == null ? 0 : Convert.ToInt32(page);
            string sqlStr = "1=1";
            if (typeid != null)
            {
                sqlStr = string.Format("TypeId={0} ", typeid);
            }
            sqlStr += " order by ImgId desc";
            List<Wx_TemplateImage> listTemp = new Wx_TemplateImageLogic().GetModelList(sqlStr);
            Pagination<Wx_TemplateImage> paginateNew = new Pagination<Wx_TemplateImage>(listTemp, pageIndex, pageSize);

            List<Wx_TemplateImageType> tagList = new Wx_TemplateImageTypeLogic().GetModelList("");


            ViewBag.typeList = tagList;

            return View(paginateNew);
        }
        public ActionResult TemplateImageEdit(int? id)
        {
            Wx_TemplateImage model = new Wx_TemplateImage();
            if (id != null)
            {
                model = new Wx_TemplateImageLogic().GetModel(Convert.ToInt32(id));
            }

            List<Wx_TemplateImageType> tagList = new Wx_TemplateImageTypeLogic().GetModelList("");
            ViewBag.typeList = tagList;
            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult TemplateImageEdit(Wx_TemplateImage model, FormCollection collection)
        {
            HttpPostedFileBase thumbnail = Request.Files["thumbnail"];
            if (thumbnail != null && thumbnail.FileName != "")
            {
                string directoryPath = Server.MapPath("~/images/qrcodeBg/");
                if (!Directory.Exists(directoryPath))//不存在这个文件夹就创建这个文件夹 
                {
                    Directory.CreateDirectory(directoryPath);
                }
                string fileName = thumbnail.FileName;
                string fileExt = Path.GetExtension(fileName).ToLower();
                string logoSrc = DateTime.Now.ToString("yyyMMddHHmmss") + fileExt;
                string savepath = directoryPath + logoSrc;
                thumbnail.SaveAs(savepath);
                model.ImgSrc = logoSrc;
            }
            if (model.ImgId == 0)
                new Wx_TemplateImageLogic().Add(model);
            else
                new Wx_TemplateImageLogic().Update(model);

            return RedirectToAction("TemplateImage");

        }

        [HttpPost]
        public ActionResult TemplateImageDelete(int id)
        {
            try
            {
                if (id > 0)
                {
                    //删除图片
                    Wx_TemplateImage model = new Wx_TemplateImageLogic().GetModel(id);
                    //判断是否有此图片
                    if (!string.IsNullOrEmpty(model.ImgSrc))
                    {
                        string directoryPath = Server.MapPath("~/images/qrcodeBg/");
                        string filePath = directoryPath + model.ImgSrc;
                        if (System.IO.File.Exists(filePath))
                        {
                            System.IO.File.Delete(filePath);
                        }
                    }

                    new Wx_TemplateImageLogic().Delete(id);
                }

                return RedirectToAction("TemplateImage");
            }
            catch
            {
                return View();
            }
        }

        #endregion

        #region 门店列表

        public ActionResult QrcodeSiteList(int? page)
        {
            int pageSize = 15;
            int pageIndex = page == null ? 0 : Convert.ToInt32(page);
            string sqlStr = "1=1";
            sqlStr += " order by Id desc";
            List<Wx_QrcodeSite> listTemp = new Wx_QrcodeSiteLogic().GetModelList(sqlStr);
            Pagination<Wx_QrcodeSite> paginateNew = new Pagination<Wx_QrcodeSite>(listTemp, pageIndex, pageSize);

            return View(paginateNew);
        }

        public ActionResult QrcodeSiteDetail(int id)
        {
            Wx_QrcodeSite model = new Wx_QrcodeSiteLogic().GetModel(id);
            if (id > 0 && model != null)
            {
                return View(model);
            }
            else
            {
                return RedirectToAction("QrcodeSiteList");
            }
        }

        #endregion

        #region 查看小程序用户生成的图片

        public JsonResult GetUserUploadfiles(int pageIndex)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            List<string> imglist = new List<string>();
            //获取文件夹下所有的文件
            string directoryPath = Server.MapPath("~/images/userupload/");
            string[] sources = Directory.GetFiles(directoryPath);
            DataTable dt = new DataTable();
            dt.Columns.Add("FileName");
            dt.Columns.Add("Sort");

            for (int i = 0; i < sources.Length; i++)
            {
                DataRow dr = dt.NewRow();
                //根据路径，获得文件名称
                string uploadFileName = Path.GetFileName(sources[i]);
                string sort = uploadFileName.Split('.')[0];
                dr["FileName"] = uploadFileName;
                dr["Sort"] = sort;
                dt.Rows.Add(dr);

            }
            DataView dv = dt.DefaultView;
            dv.Sort = "Sort desc";
            dt = dv.ToTable();
            int pageSize = 20;
            int total = dt.Rows.Count;
            int pageCount = total / pageSize;
            for (int i = pageIndex * pageSize; i < dt.Rows.Count && i < (pageIndex + 1) * pageSize; i++)
            {
                imglist.Add(dt.Rows[i]["FileName"].ToString());
            }

            dic.Add("imglist", imglist);
            dic.Add("total", dt.Rows.Count);
            dic.Add("pageSize", pageSize);
            dic.Add("state", "success");

            return Json(dic);
        }

        public JsonResult DelUserUploadfiles()
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            string imgName = Request["imgname"].ToString();
            //判断是否有此图片
            string directoryPath = Server.MapPath("~/images/userupload/");
            string filePath = directoryPath + imgName;
            if (System.IO.File.Exists(filePath))
            {
                System.IO.File.Delete(filePath);
            }
            dic.Add("state", "success");

            return Json(dic);
        }

        //门店站点生成的图片
        public JsonResult GetSiteUploadfiles(int pageIndex)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            List<object> imglist = new List<object>();
            //获取文件夹下所有的文件
            string directoryPath = Server.MapPath("~/images/qrcodesite/");
            string[] sources = Directory.GetFiles(directoryPath);
            DataTable dt = new DataTable();
            dt.Columns.Add("FileName");
            dt.Columns.Add("Sort");

            for (int i = 0; i < sources.Length; i++)
            {
                DataRow dr = dt.NewRow();
                //根据路径，获得文件名称
                string uploadFileName = Path.GetFileName(sources[i]);
                string sort = uploadFileName.Split('.')[0];
                if (sort.IndexOf("-") > -1)
                {
                    sort = sort.Split('-')[1];
                }
                dr["FileName"] = uploadFileName;
                dr["Sort"] = sort;
                dt.Rows.Add(dr);
            }

            DataView dv = dt.DefaultView;
            dv.Sort = "Sort desc";
            dt = dv.ToTable();
            int pageSize = 20;
            int total = dt.Rows.Count;
            int pageCount = total / pageSize;
            for (int i = pageIndex * pageSize; i < dt.Rows.Count && i < (pageIndex + 1) * pageSize; i++)
            {
                string filename = dt.Rows[i]["FileName"].ToString();
                string sort = filename.Split('.')[0];
                if (sort.IndexOf("-") > -1)
                {
                    int len = sort.Split('-').Length;
                    sort = sort.Split('-')[len - 1];
                    sort = "2017-" + sort.Substring(0, 2) + "-" + sort.Substring(2, 2) + " " + sort.Substring(4, 2) + ":" + sort.Substring(6, 2);
                }
                //判断这个文件是否在数据库中
                object obj = new
                {
                    file = filename,
                    isExisted = isExisted(filename),
                    sort = sort
                };

                imglist.Add(obj);
            }

            dic.Add("imglist", imglist);
            dic.Add("total", dt.Rows.Count);
            dic.Add("pageSize", pageSize);
            dic.Add("state", "success");

            return Json(dic);
        }

        public JsonResult DelSiteUploadfiles()
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            string imgName = Request["imgname"].ToString();
            //判断是否有此图片
            if (!isExisted(imgName))
            {
                string directoryPath = Server.MapPath("~/images/qrcodesite/");
                string filePath = directoryPath + imgName;
                if (System.IO.File.Exists(filePath))
                {
                    System.IO.File.Delete(filePath);
                }
                dic.Add("state", "success");
            }
            else
            {
                dic.Add("state", "fail");
            }
            return Json(dic);
        }

        private bool isExisted(string filename)
        {
            string strSql = string.Format("CompanyImg1 like '%{0}' or CompanyImg2 like '%{0}' or CompanyImg3 like '%{0}'", filename);
            int existCount = new Wx_QrcodeSiteLogic().GetRecordCount(strSql);
            if (existCount > 0)
                return true;
            else
                return false;

        }

        #endregion

        #region 小程序接口
        //
        // 纯文本二维码
        public ActionResult QrcodeByTxt(string txt, string png, string b)
        {
            txt = string.IsNullOrEmpty(txt) ? "在线二维码" : txt;
            bool isTransparent = png == "1" ? true : false;
            bool border = b == "1" ? true : false;
            System.Drawing.Image image = GetQrcode(txt, "", "", isTransparent, border);
            System.IO.MemoryStream memory = new System.IO.MemoryStream();
            image.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
            Byte[] buffer = memory.GetBuffer();
            Response.ContentType = "image/png";
            Response.OutputStream.Write(buffer, 0, buffer.Length);

            return View();
        }

        public ActionResult ReverseQrcodeByTxt(string txt, string png, string b, string c)
        {
            txt = string.IsNullOrEmpty(txt) ? "在线二维码" : txt;
            bool isTransparent = png == "1" ? true : false;
            bool border = b == "1" ? true : false;
            System.Drawing.Image image = GetColorQrcode(txt, "#ffffff", c, isTransparent, border);
            System.IO.MemoryStream memory = new System.IO.MemoryStream();
            image.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
            Byte[] buffer = memory.GetBuffer();
            Response.ContentType = "image/png";
            Response.OutputStream.Write(buffer, 0, buffer.Length);

            return View();
        }

        public ActionResult ColorQrcodeByTxt(string txt, string png, string b, string c)
        {
            txt = string.IsNullOrEmpty(txt) ? "在线二维码" : txt;
            bool isTransparent = png == "1" ? true : false;
            bool border = b == "1" ? true : false;
            System.Drawing.Image image = GetQrcode(txt, "", c, isTransparent, border);
            System.IO.MemoryStream memory = new System.IO.MemoryStream();
            image.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
            Byte[] buffer = memory.GetBuffer();
            Response.ContentType = "image/png";
            Response.OutputStream.Write(buffer, 0, buffer.Length);

            return View();
        }

        // 上传用户制作的图片（生成的二维码）
        public JsonResult UploadUserImage()
        {
            HttpFileCollectionBase files = Request.Files;
            if (files.Count > 0)
            {
                string directoryPath = Server.MapPath("~/images/userupload/");
                if (!Directory.Exists(directoryPath))//不存在这个文件夹就创建这个文件夹 
                {
                    Directory.CreateDirectory(directoryPath);
                }
                string fileName = files[0].FileName;
                string extName = Path.GetExtension(fileName).ToLower();


                extName = string.IsNullOrEmpty(extName) ? ".jpg" : extName;
                if (extName == ".dat")
                    extName = ".jpg";
                string path = DateTime.Now.ToString("yyyyMMddHHmmssfff") + extName;
                string savepath = directoryPath + path;

                Log.LogNote("上传制作的图片", "fileName=" + fileName + "===>>>path=" + path, "weapp");

                //如果图片大于100k，进行压缩
                if (files[0].ContentLength > 1024 * 100)
                {
                    Image img = fileToImage(files[0]);
                    if (!ReduceImage(img, savepath, 50))
                        files[0].SaveAs(savepath);
                }
                else
                {
                    files[0].SaveAs(savepath);
                }
            }

            var obj = new
            {
                state = "success"
            };

            return Json(obj);
        }

        //获取Openid
        [HttpPost]
        public JsonResult GetOpenid(string code)
        {
            string openid = "";
            string state = "fail";
            if (!string.IsNullOrEmpty(code))
            {
                string url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + AppId + "&secret=" + AppSecret + "&js_code=" + code + "&grant_type=authorization_code";
                //string url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + AppId + "&secret=" + AppSecret + "&code=" + code + "&grant_type=authorization_code";
                var response = HttpWebResponseUtility.CreateGetHttpResponse(url, null, string.Empty, null);
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("UTF-8"));
                string retString = myStreamReader.ReadToEnd();
                GetOpenidModel rj = Serializer.Deserialize<GetOpenidModel>(retString);
                if (!string.IsNullOrEmpty(rj.openid))
                {
                    openid = rj.openid;
                    state = "success";
                }
            }

            var obj = new
            {
                state = state,
                openid = openid
            };

            return Json(obj);
        }

        // 上传的图片（店铺）
        public JsonResult UploadQrcodeSiteImage()
        {
            string state = "fail";
            string distPath = "";
            try
            {
                HttpFileCollectionBase files = Request.Files;
                if (files.Count > 0)
                {
                    string openid = Request.Form["openid"].ToString();
                    string directoryPath = Server.MapPath("~/images/qrcodesite/" + openid + "/");
                    if (!Directory.Exists(directoryPath))//不存在这个文件夹就创建这个文件夹 
                    {
                        Directory.CreateDirectory(directoryPath);
                    }
                    string fileName = files[0].FileName;
                    string extName = Path.GetExtension(fileName).ToLower();


                    extName = string.IsNullOrEmpty(extName) ? ".jpg" : extName;
                    if (extName == ".dat" || extName == ".html")
                        extName = ".jpg";
                    string path = DateTime.Now.ToString("MMddHHmmssfff") + extName;
                    string savepath = directoryPath + path;

                    //如果图片大于100k，进行压缩
                    if (files[0].ContentLength > 1024 * 100)
                    {
                        Image img = fileToImage(files[0]);
                        if (!ReduceImage(img, savepath, 50))
                            files[0].SaveAs(savepath);
                    }
                    else
                    {
                        files[0].SaveAs(savepath);
                    }
                    distPath = "https://www.see2eyes.cn/images/qrcodesite/" + openid + "/" + path;
                    state = "success";
                }
            }
            catch (Exception ex)
            {
                state = "fail";
            }

            var obj = new
            {
                state = state,
                src = distPath
            };

            return Json(obj);
        }

        public JsonResult SearchQrcodeSiteData(string openid)
        {
            string state = "fail";
            Wx_QrcodeSite model = new Wx_QrcodeSite();
            try
            {
                if (!string.IsNullOrEmpty(openid))
                {
                    List<Wx_QrcodeSite> list = new Wx_QrcodeSiteLogic().GetModelList("IsLock=1 and openid='" + openid + "'");
                    if (list.Count > 0)
                    {
                        model = list.FirstOrDefault();
                        state = "success";
                    }
                }
            }
            catch (Exception ex)
            {
                state = "fail";
            }

            var obj = new
            {
                state = state,
                model = model
            };

            return Json(obj);
        }

        //添加或修改店铺信息
        public JsonResult UpdateQrcodeSiteData(Wx_QrcodeSite model)
        {
            string state = "fail";
            try
            {
                string openid = model.Openid;
                if (!string.IsNullOrEmpty(openid))
                {
                    model.UpdateDate = DateTime.Now;
                    //查询是否存在老数据
                    List<Wx_QrcodeSite> list = new Wx_QrcodeSiteLogic().GetModelList("IsLock=1 and openid='" + openid + "'");
                    if (list.Count > 0)
                    {
                        Wx_QrcodeSite oldModel = list.FirstOrDefault();
                        oldModel.Company = model.Company;
                        oldModel.Address = model.Address;
                        oldModel.OpenidHours = model.OpenidHours;
                        oldModel.Telephone = model.Telephone;
                        oldModel.Introduce = model.Introduce;
                        oldModel.CompanyImg1 = model.CompanyImg1;
                        oldModel.CompanyImg2 = model.CompanyImg2;
                        oldModel.CompanyImg3 = model.CompanyImg3;
                        oldModel.Latitude = model.Latitude;
                        oldModel.Longitude = model.Longitude;
                        oldModel.UpdateDate = model.UpdateDate;
                        if (string.IsNullOrEmpty(oldModel.QrcodeImg))
                        {
                            oldModel.QrcodeImg = CreateWxappQrcodeImage(openid);
                        }
                        new Wx_QrcodeSiteLogic().Update(oldModel);
                        model.Id = oldModel.Id;
                    }
                    else
                    {
                        //新生成的数据要生成一个小程序二维码
                        model.QrcodeImg = CreateWxappQrcodeImage(openid);
                        model.IsLock = true;
                        model.CreateDate = DateTime.Now;
                        model.Id = new Wx_QrcodeSiteLogic().Add(model);
                    }
                    if (model.Id > 0)
                        state = "success";
                }
            }
            catch (Exception ex)
            {
                state = "fail";
            }

            var obj = new
            {
                state = state
            };

            return Json(obj);
        }

        //添加或修改商品
        public JsonResult UpdateShopProduct(Wx_Shop_Product model)
        {
            string state = "fail";
            int pid = 0;
            try
            {
                if (model.ShopId > 0)
                {
                    if (model.Pid > 0)
                    {
                        Wx_Shop_Product oldModel = new Wx_Shop_ProductLogic().GetModel(model.Pid);
                        if (oldModel != null)
                        {
                            oldModel.ProductName = model.ProductName;
                            oldModel.Price = model.Price;
                            oldModel.Thumb = model.Thumb;
                            oldModel.Introduce = model.Introduce;
                            new Wx_Shop_ProductLogic().Update(oldModel);
                            state = "success";
                            pid = model.Pid;
                        }
                    }
                    else
                    {
                        model.Sort = 0;
                        model.CreateTime = DateTime.Now;
                        pid = new Wx_Shop_ProductLogic().Add(model);
                        if (pid > 0)
                            state = "success";
                    }
                }
            }
            catch (Exception ex)
            {
                state = "fail";
            }
            var obj = new
            {
                state = state,
                pid = pid
            };
            return Json(obj);
        }

        //获取商品列表
        public JsonResult GetShopProductList(int shopid)
        {
            string state = "fail";
            List<Wx_Shop_Product> list = new List<Wx_Shop_Product>();
            try
            {
                if (shopid > 0)
                {
                    list = new Wx_Shop_ProductLogic().GetModelList("ShopId=" + shopid);
                    state = "success";
                }
            }
            catch (Exception ex)
            {
                state = "fail";
            }
            var obj = new
            {
                state = state,
                list = list
            };
            return Json(obj);
        }

        //获取商品详细
        public JsonResult GetShopProductDetail(int pid)
        {
            string state = "fail";
            Wx_Shop_Product model = new Wx_Shop_Product();
            try
            {
                if (pid > 0)
                {
                    model = new Wx_Shop_ProductLogic().GetModel(pid);
                    state = "success";
                }
            }
            catch (Exception ex)
            {
                state = "fail";
            }
            var obj = new
            {
                state = state,
                model = model
            };
            return Json(obj);
        }

        //删除商品
        public JsonResult DelShopProductDetail(int pid)
        {
            string state = "fail";
            try
            {
                if (pid > 0)
                {
                    bool isDel = new Wx_Shop_ProductLogic().Delete(pid);
                    if (isDel)
                        state = "success";
                }
            }
            catch (Exception ex)
            {
                state = "fail";
            }
            var obj = new
            {
                state = state
            };
            return Json(obj);
        }


        //添加或修改店铺首页控件
        public JsonResult UpdateShopComponent(Wx_Shop_Component model)
        {
            string state = "fail";
            int comid = 0;
            try
            {
                if (model.ShopId > 0)
                {
                    if (model.ComId > 0)
                    {
                        Wx_Shop_Component oldModel = new Wx_Shop_ComponentLogic().GetModel(model.ComId);
                        if (oldModel != null)
                        {
                            oldModel.ComName = model.ComName;
                            oldModel.ComContent = model.ComContent;
                            new Wx_Shop_ComponentLogic().Update(oldModel);
                            state = "success";
                            comid = model.ComId;
                        }
                    }
                    else
                    {
                        model.Sort = 0;
                        comid = new Wx_Shop_ComponentLogic().Add(model);
                        if (comid > 0)
                            state = "success";
                    }
                }
            }
            catch (Exception ex)
            {
                state = "fail";
            }
            var obj = new
            {
                state = state,
                comid = comid
            };
            return Json(obj);
        }


        //获取背景图片模板
        public string GetTemplateImage()
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            List<Wx_TemplateImageType> listTemp = new Wx_TemplateImageTypeLogic().GetModelList("1=1 order by Sort desc, TypeId desc");
            List<object> jsonStr = new List<object>();
            foreach (var imgType in listTemp)
            {
                int typeid = imgType.TypeId;

                string sqlStr = string.Format("TypeId={0} ", typeid);
                sqlStr += " order by Sort desc,ImgId desc";
                List<Wx_TemplateImage> listBg = new Wx_TemplateImageLogic().GetModelList(sqlStr);

                var obj = new
                {
                    TypeName = imgType.TypeName,
                    TypeId = imgType.TypeId,
                    Images = listBg
                };
                jsonStr.Add(obj);
            }

            return Serializer.Serialize(jsonStr);
        }

        //生成小程序二维码
        public string CreateWxappQrcodeImage(string openid)
        {
            string fileName = "";
            try
            {
                List<MP_Setting> list = new MP_SettingLogic().GetModelList("AppId='" + AppId + "' and RefreshEnable=1");
                if (list.Count > 0)
                {
                    MP_Setting model = list.FirstOrDefault();

                    //小程序码
                    //https://api.weixin.qq.com/wxa/getwxacode?access_token=ACCESS_TOKEN
                    //小程序二维码
                    //https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=ACCESS_TOKEN

                    string posturl = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + model.AccessToken;
                    string postData = "{\"path\": \"pages/site/detail?openid=" + openid + "\", \"width\": 430}";
                    var request = HttpWebResponseUtility.CreatePostHttpResponse(posturl, postData, null, string.Empty, Encoding.UTF8, null);
                    Bitmap img = new Bitmap(request.GetResponseStream());//获取图片流   
                    string directoryPath = Server.MapPath("~/images/qrcode/site/");
                    if (!Directory.Exists(directoryPath))//不存在这个文件夹就创建这个文件夹 
                    {
                        Directory.CreateDirectory(directoryPath);
                    }
                    fileName = openid + ".jpg";
                    string savepath = directoryPath + fileName;
                    img.Save(savepath, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
            }
            catch (Exception ex)
            {
            }

            return fileName;
        }

        #endregion


        //
        // 带logo的二维码
        public ActionResult QrcodeWithLogo(string txt)
        {
            txt = string.IsNullOrEmpty(txt) ? "在线二维码" : txt;
            System.Drawing.Image imageSource = GetQrcode(txt, "", "", false, true);
            System.Drawing.Image image = new System.Drawing.Bitmap(10, 10);

            HttpFileCollectionBase files = Request.Files;
            if (files.Count > 0)
            {
                HttpPostedFileBase thumbnail = files[0];
                Image img = fileToImage(thumbnail);
                image = CombinImage(imageSource, img);
            }
            else
            {
                //image = imageSource;
                string path = Server.MapPath("../images/qingcai.jpg");
                image = CombinImage(imageSource, path);
            }

            System.IO.MemoryStream memory = new System.IO.MemoryStream();
            image.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
            Byte[] buffer = memory.GetBuffer();
            Response.ContentType = "image/png";
            Response.OutputStream.Write(buffer, 0, buffer.Length);
            //图片转成base64返回
            return View();
        }


        //带背景图片
        public ActionResult QrcodeWithBackground(string txt)
        {
            txt = string.IsNullOrEmpty(txt) ? "个性化二维码生成器" : txt;
            QRCodeEncoder QREncoder = new QRCodeEncoder();
            QREncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
            QREncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
            QREncoder.QRCodeVersion = 7;
            QREncoder.QRCodeScale = 4;
            Bitmap bmp = QREncoder.Encode(txt);
            int height = bmp.Height;
            int width = bmp.Width;
            string path = Server.MapPath("../images/backPicture.jpg");
            Bitmap back = (Bitmap)KiResizeImage(new Bitmap(path), width, height, 0);

            int backWid = back.Width;
            int backHigh = back.Height;
            for (int h = 0; h < height; h++)
            {
                for (int w = 0; w < width; w++)
                {
                    ////把黑点换成图片颜色
                    //if (w <= backWid && h <= backHigh && bmp.GetPixel(w, h).R == 0 && bmp.GetPixel(w, h).G == 0 && bmp.GetPixel(w, h).B == 0)
                    //{
                    //    //如果背景图片此像素位置不是白点
                    //    if (back.GetPixel(w, h).R != 255 && back.GetPixel(w, h).G != 255 && back.GetPixel(w, h).B != 255)
                    //    {
                    //        bmp.SetPixel(w, h, back.GetPixel(w, h));
                    //    }
                    //    //如果是白色底图，透明、灰度化
                    //    else
                    //    {
                    //        Color bgC = back.GetPixel(w, h);
                    //        Color colorNew = System.Drawing.Color.FromArgb(30, bgC.B, bgC.B, bgC.B);
                    //        bmp.SetPixel(w, h, colorNew);
                    //    }                        
                    //}

                    //如果是黑点，则显示图片对应点相应的颜色
                    if (bmp.GetPixel(w, h).R == 0 && bmp.GetPixel(w, h).G == 0 && bmp.GetPixel(w, h).B == 0)
                    {
                        //如果背景图片此像素位置是白点,则显示黑色
                        if (back.GetPixel(w, h).R != 255 && back.GetPixel(w, h).G != 255 && back.GetPixel(w, h).B != 255)
                        {
                            bmp.SetPixel(w, h, back.GetPixel(w, h));
                        }

                    }
                    //如果是白色底图，则显示图片对应点相应的颜色的透明色
                    else
                    {
                        Color bgC = back.GetPixel(w, h);
                        Color colorNew = System.Drawing.Color.FromArgb(30, bgC.B, bgC.B, bgC.B);
                        bmp.SetPixel(w, h, colorNew);
                    }
                }
            }

            System.IO.MemoryStream memory = new System.IO.MemoryStream();
            bmp.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
            Byte[] buffer = memory.GetBuffer();
            Response.ContentType = "image/png";
            Response.OutputStream.Write(buffer, 0, buffer.Length);
            //图片转成base64返回
            return View();
        }


        public ActionResult QrcodeWithIcon(string txt, string icon)
        {
            txt = string.IsNullOrEmpty(txt) ? "个性化二维码生成器" : txt;
            QRCodeEncoder QREncoder = new QRCodeEncoder();
            QREncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
            QREncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
            QREncoder.QRCodeVersion = 0;
            QREncoder.QRCodeScale = 1;
            Bitmap bmp = QREncoder.Encode(txt, System.Text.Encoding.UTF8);
            int height = bmp.Height - 1;
            int width = bmp.Width - 1;
            string iconPath = Server.MapPath("../images/emoji/heart2.png");
            System.Drawing.Image imgIcon = System.Drawing.Image.FromFile(iconPath);        //照片图片
            Color txtColor = Color.Red;
            if (icon == "blackheart")
            {
                iconPath = Server.MapPath("../images/emoji/heart3.png");
                txtColor = System.Drawing.Color.FromArgb(255, 0, 0, 0);
            }
            else if (icon == "blackdot")
            {
                iconPath = "";
                txtColor = System.Drawing.Color.FromArgb(255, 0, 0, 0);
            }
            else if (icon == "star")
            {
                iconPath = Server.MapPath("../images/emoji/star.png");
                txtColor = System.Drawing.Color.FromArgb(255, 0, 0, 0);
            }
            else if (icon == "face")
            {
                iconPath = Server.MapPath("../images/emoji/face.jpg");
                txtColor = System.Drawing.ColorTranslator.FromHtml("#F7D359");
            }
            else if (icon == "lei")
            {
                iconPath = Server.MapPath("../images/emoji/lei.jpg");
                txtColor = System.Drawing.Color.FromArgb(255, 0, 0, 0);
            }
            else if (icon == "shuai")
            {
                iconPath = Server.MapPath("../images/emoji/shuai.jpg");
                txtColor = System.Drawing.Color.FromArgb(255, 0, 0, 0);
            }
            else if (icon == "andr")
            {
                iconPath = Server.MapPath("../images/emoji/andr.jpg");
                txtColor = System.Drawing.Color.FromArgb(255, 0, 0, 0);
            }
            else if (icon == "apple")
            {
                iconPath = Server.MapPath("../images/emoji/apple.jpg");
                txtColor = System.Drawing.Color.FromArgb(255, 0, 0, 0);
            }
            else if (icon == "header")
            {
                iconPath = Server.MapPath("../images/emoji/header.jpg");
                txtColor = System.Drawing.Color.FromArgb(255, 0, 0, 0);
            }
            else if (icon == "ie")
            {
                iconPath = Server.MapPath("../images/emoji/ie.jpg");
                txtColor = System.Drawing.Color.FromArgb(255, 0, 0, 0);
            }

            else if (icon == "qq")
            {
                iconPath = Server.MapPath("../images/emoji/qq.jpg");
                txtColor = System.Drawing.Color.FromArgb(255, 0, 0, 0);
            }
            else if (icon == "star")
            {
                iconPath = Server.MapPath("../images/emoji/star.jpg");
                txtColor = System.Drawing.Color.FromArgb(255, 0, 0, 0);
            }
            else if (icon == "sun")
            {
                iconPath = Server.MapPath("../images/emoji/sun.jpg");
                txtColor = System.Drawing.Color.FromArgb(255, 0, 0, 0);
            }
            else if (icon == "water")
            {
                iconPath = Server.MapPath("../images/emoji/water.jpg");
                txtColor = System.Drawing.Color.FromArgb(255, 0, 0, 0);
            }

            int iconWidth = 25;
            int iconHeight = 25;
            if (iconPath != "")
            {
                imgIcon = System.Drawing.Image.FromFile(iconPath);
            }

            Bitmap bmpNew = new Bitmap(width * iconWidth, height * iconHeight);
            Graphics g = Graphics.FromImage(bmpNew);
            g.FillRectangle(Brushes.White, 0, 0, width * iconWidth, height * iconHeight);

            SolidBrush brushTxt = new SolidBrush(txtColor);
            SolidBrush brushBg = new SolidBrush(Color.White);
            //三个定位点不能变化
            int pos = 7;
            for (int h = 0; h < height; h++)
            {
                for (int w = 0; w < width; w++)
                {
                    ////把黑点换成图片                                    
                    if (bmp.GetPixel(w, h).R == 0 && bmp.GetPixel(w, h).G == 0 && bmp.GetPixel(w, h).B == 0)
                    {
                        if ((w <= pos && h <= pos) || (w <= pos && h >= height - pos) || (w >= width - pos && h <= pos))
                        {
                            //定位点中间使用图片替代
                            if ((w == 0 || w == width - 1 || w == pos - 1 || w == width - pos || h == 0 || h == height - 1 || h == pos - 1 || h == height - pos))
                            {
                                g.FillEllipse(brushTxt, w * iconWidth, h * iconHeight, iconWidth, iconHeight);
                            }
                            else if ((w == 2 && h == 2) || (w == 2 && h == height - 5) || (w == width - 5 && h == 2))
                            {
                                //if (iconPath != "")
                                //    g.DrawImage(imgIcon, w * iconWidth, h * iconHeight, iconWidth * 3, iconHeight * 3);
                                //else
                                //    g.FillEllipse(brushTxt, w * iconWidth, h * iconHeight, iconWidth * 3, iconHeight * 3);
                                g.FillEllipse(brushTxt, w * iconWidth, h * iconHeight, iconWidth * 3, iconHeight * 3);
                            }
                        }
                        else
                        {
                            if (iconPath != "")
                                g.DrawImage(imgIcon, w * iconWidth, h * iconHeight, iconWidth, iconHeight);
                            else
                                g.FillEllipse(brushTxt, w * iconWidth, h * iconHeight, iconWidth, iconHeight);
                        }
                    }

                }

            }

            GC.Collect();
            g.Dispose();

            System.IO.MemoryStream memory = new System.IO.MemoryStream();
            bmpNew.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
            Byte[] buffer = memory.GetBuffer();
            Response.ContentType = "image/png";
            Response.OutputStream.Write(buffer, 0, buffer.Length);
            return View();

        }

        /// <summary>  
        /// 生成二维码.  
        /// </summary>  
        /// <param name="data">需要添加进去的文本</param>  
        /// <param name="BgColor">背景色</param>  
        /// <param name="TxtColor">前景色</param>  
        /// <param name="isTransparent">是否透明</param>
        /// <param name="hasBorder">是否有边框（二维码宽度的10分之一）</param>  
        /// <returns></returns>   
        public System.Drawing.Image GetQrcode(String data, string BgColor, string TxtColor, bool isTransparent, bool hasBorder)
        {
            QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
            qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
            //每个点所占的像素
            qrCodeEncoder.QRCodeScale = 5;
            //qrCodeEncoder.QRCodeVersion = 7;
            //为0时，根据内容自动扩展
            qrCodeEncoder.QRCodeVersion = 0;


            TxtColor = string.IsNullOrEmpty(TxtColor) ? "#000000" : TxtColor;
            BgColor = string.IsNullOrEmpty(BgColor) ? "#ffffff" : BgColor;
            var bgColor = System.Drawing.ColorTranslator.FromHtml(BgColor);
            //设置背景透明
            if (isTransparent)
            {
                //值越小，越透明
                //bgColor = System.Drawing.Color.FromArgb(100, 255, 255, 255);
                bgColor = System.Drawing.Color.FromArgb(0, 255, 255, 255);
            }

            qrCodeEncoder.QRCodeBackgroundColor = bgColor;
            qrCodeEncoder.QRCodeForegroundColor = System.Drawing.ColorTranslator.FromHtml(TxtColor);
            //qrCodeEncoder.QRCodeForegroundColor = System.Drawing.Color.FromArgb(100, 250, 0, 0);

            qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H;
            var pbImg = qrCodeEncoder.Encode(data, System.Text.Encoding.UTF8);
            var width = pbImg.Width / 10;
            //加边框
            if (!hasBorder)
            {
                width = 0;
            }
            var dwidth = width * 2;
            Bitmap bmp = new Bitmap(pbImg.Width + dwidth, pbImg.Height + dwidth);
            Graphics g = Graphics.FromImage(bmp);

            g.FillRectangle(new SolidBrush(bgColor), 0, 0, pbImg.Width + dwidth, pbImg.Height + dwidth);
            g.DrawImage(pbImg, width, width);
            g.Dispose();
            return bmp;
        }

        /// <summary>  
        /// 生成二维码--颜色反转.  
        /// </summary>  
        /// <param name="data">需要添加进去的文本</param>  
        /// <param name="BgColor">背景色</param>  
        /// <param name="TxtColor">前景色（不能透明）</param>  
        /// <param name="isTransparent">是否透明</param>
        /// <param name="hasBorder">是否有边框（二维码宽度的10分之一）</param>  
        /// <returns></returns>   
        public System.Drawing.Image GetColorQrcode(String data, string BgColor, string TxtColor, bool isTransparent, bool hasBorder)
        {
            QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
            qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
            qrCodeEncoder.QRCodeScale = 5;
            //qrCodeEncoder.QRCodeVersion = 7;
            qrCodeEncoder.QRCodeVersion = 0;

            TxtColor = string.IsNullOrEmpty(TxtColor) ? "#ffffff" : TxtColor;
            BgColor = string.IsNullOrEmpty(BgColor) ? "#000000" : BgColor;
            var bgColor = System.Drawing.ColorTranslator.FromHtml(BgColor);
            var txtColor = System.Drawing.ColorTranslator.FromHtml(TxtColor);
            //设置背景透明
            if (isTransparent)
            {
                //值越小，越透明
                //bgColor = System.Drawing.Color.FromArgb(100, 255, 255, 255);
                txtColor = System.Drawing.Color.FromArgb(0, 255, 255, 255);
            }

            qrCodeEncoder.QRCodeBackgroundColor = bgColor;
            qrCodeEncoder.QRCodeForegroundColor = txtColor;
            //qrCodeEncoder.QRCodeForegroundColor = System.Drawing.Color.FromArgb(100, 250, 0, 0);

            qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H;
            var pbImg = qrCodeEncoder.Encode(data, System.Text.Encoding.UTF8);
            var width = pbImg.Width / 10;
            //加边框
            if (!hasBorder)
            {
                width = 0;
            }
            var dwidth = width * 2;
            Bitmap bmp = new Bitmap(pbImg.Width + dwidth, pbImg.Height + dwidth);
            Graphics g = Graphics.FromImage(bmp);

            g.FillRectangle(new SolidBrush(bgColor), 0, 0, pbImg.Width + dwidth, pbImg.Height + dwidth);
            g.DrawImage(pbImg, width, width);
            g.Dispose();
            return bmp;
        }


        /// <summary>  
        /// 调用此函数后使此两种图片合并，类似相册，有个  
        /// 背景图，中间贴自己的目标图片  
        /// </summary>  
        /// <param name="sourceImg">粘贴的源图片</param>  
        /// <param name="destImg">粘贴的目标图片</param>  
        public static System.Drawing.Image CombinImage(System.Drawing.Image imgBack, string destImg)
        {

            System.Drawing.Image img = System.Drawing.Image.FromFile(destImg);        //照片图片    
            if (img.Height != 50 || img.Width != 50)
            {
                img = KiResizeImage(img, 50, 50, 0);
            }
            Graphics g = Graphics.FromImage(imgBack);

            g.DrawImage(imgBack, 0, 0, imgBack.Width, imgBack.Height);      //g.DrawImage(imgBack, 0, 0, 相框宽, 相框高);   

            //g.FillRectangle(System.Drawing.Brushes.White, imgBack.Width / 2 - img.Width / 2 - 1, imgBack.Width / 2 - img.Width / 2 - 1,1,1);//相片四周刷一层黑色边框  

            //g.DrawImage(img, 照片与相框的左边距, 照片与相框的上边距, 照片宽, 照片高);  

            g.DrawImage(img, imgBack.Width / 2 - img.Width / 2, imgBack.Width / 2 - img.Width / 2, img.Width, img.Height);
            GC.Collect();
            return imgBack;
        }
        public static System.Drawing.Image CombinImage(System.Drawing.Image imgBack, System.Drawing.Image imgLogo)
        {
            if (imgLogo.Height != 50 || imgLogo.Width != 50)
            {
                imgLogo = KiResizeImage(imgLogo, 50, 50, 0);
            }
            Graphics g = Graphics.FromImage(imgBack);

            g.DrawImage(imgBack, 0, 0, imgBack.Width, imgBack.Height);      //g.DrawImage(imgBack, 0, 0, 相框宽, 相框高);   

            //g.FillRectangle(System.Drawing.Brushes.White, imgBack.Width / 2 - img.Width / 2 - 1, imgBack.Width / 2 - img.Width / 2 - 1,1,1);//相片四周刷一层黑色边框  

            //g.DrawImage(img, 照片与相框的左边距, 照片与相框的上边距, 照片宽, 照片高);  

            g.DrawImage(imgLogo, imgBack.Width / 2 - imgLogo.Width / 2, imgBack.Width / 2 - imgLogo.Width / 2, imgLogo.Width, imgLogo.Height);
            GC.Collect();
            return imgBack;
        }

        /// <summary>  
        /// Resize图片  
        /// </summary>  
        /// <param name="bmp">原始Bitmap</param>  
        /// <param name="newW">新的宽度</param>  
        /// <param name="newH">新的高度</param>  
        /// <param name="Mode">保留着，暂时未用</param>  
        /// <returns>处理以后的图片</returns>  
        public static System.Drawing.Image KiResizeImage(System.Drawing.Image bmp, int newW, int newH, int Mode)
        {
            try
            {
                System.Drawing.Image b = new Bitmap(newW, newH);
                Graphics g = Graphics.FromImage(b);

                // 插值算法的质量  
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
                g.Dispose();

                return b;
            }
            catch
            {
                return null;
            }
        }

        public static bool ReduceImage(Image iSource, string outPath, int flag)
        {
            ImageFormat tFormat = iSource.RawFormat;
            EncoderParameters ep = new EncoderParameters();
            long[] qy = new long[1];
            qy[0] = flag;
            EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
            ep.Param[0] = eParam;
            try
            {
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageDecoders();
                ImageCodecInfo jpegICIinfo = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[x];
                        break;
                    }
                }
                if (jpegICIinfo != null)
                    iSource.Save(outPath, jpegICIinfo, ep);
                else
                    iSource.Save(outPath, tFormat);
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                iSource.Dispose();
            }
        }

        private Image fileToImage(HttpPostedFileBase file)
        {
            MemoryStream ms = new MemoryStream();
            string file_etx = Path.GetExtension(file.FileName).ToLower();
            Image img = new Bitmap(file.InputStream);
            switch (file_etx)
            {
                case ".jpg":
                    img.Save(ms, ImageFormat.Jpeg);
                    break;
                case ".png":
                    img.Save(ms, ImageFormat.Png);
                    break;
                case ".gif":
                    img.Save(ms, ImageFormat.Gif);
                    break;
                case ".bmp":
                    img.Save(ms, ImageFormat.Bmp);
                    break;
                default:
                    img.Save(ms, ImageFormat.Jpeg);
                    break;
            }
            return img;
        }
    }
}
